#include <QDebug>
#include "UserPersonal_ui.h"
#include "UserPersonal_ui_logic.h"
#include<QSplitter>
#include"globals.h"

UserPersonal::UserPersonal(QWidget *parent)
    : QWidget(parent)
{

    if (uplogic == nullptr) {
        uplogic = new UserPersonalLogic();
    }
    init(); // 调用初始化函数
    fetchOrderList();

}


void UserPersonal::init()
{
    // Initialize the splitter layout for two sections
    QSplitter *splitter = new QSplitter(Qt::Vertical, this);

    // Personal Info Section
    QWidget *personalInfoWidget = new QWidget(this);
    QVBoxLayout *personalInfoLayout = new QVBoxLayout(personalInfoWidget);
    showPersonalInfo(personalInfoLayout);  // Set up the personal info section
    personalInfoWidget->setLayout(personalInfoLayout);
    personalInfoWidget->setMinimumHeight(150);  // Control the height of the personal info section

    // Order Management Section
    orderManageWidget = new QWidget(this);
    orderLayout = new QVBoxLayout(orderManageWidget);

      // Set up the order management section
    orderManageWidget->setLayout(orderLayout);
    splitter->addWidget(personalInfoWidget);
    splitter->addWidget(orderManageWidget);

    // Set initial sizes for each section to balance heights
    splitter->setSizes(QList<int>() << 300 << 300);

    // Set the main layout to use the splitter
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(splitter);
    setLayout(mainLayout);
}

QString UserPersonal::buttonStyle()
{
    return "QPushButton {"
           "background-color: lightblue;"
           "border: 2px solid darkblue;"
           "border-radius: 10px;"
           "}"
           "QPushButton:hover {"
           "background-color: blue;"
           "color: white;"
           "}";
}




void UserPersonal::showPersonalInfo(QVBoxLayout *infoLayout)
{
    // Create a vertical layout for the title and avatar
    QVBoxLayout *headerLayout = new QVBoxLayout();

    // Create and style the "个人信息" title label
    QLabel *titleLabel = new QLabel(tr("个人信息"), this);
    titleLabel->setAlignment(Qt::AlignCenter);  // Center align the title
    titleLabel->setStyleSheet("font-size: 20px; font-weight: bold;");  // Set font size and bold

    // Create the avatar label
    avatarLabel = new QLabel(this);
    QPixmap avatarPixmap(":/icon/logo.png");
    QPixmap scaledImage = avatarPixmap.scaled(100, 150, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    avatarLabel->setPixmap(scaledImage);
    avatarLabel->setFixedSize(100, 100);
    avatarLabel->setFrameStyle(QFrame::Box | QFrame::Raised);
    avatarLabel->setAlignment(Qt::AlignCenter);

    // Add the title label and avatar to the header layout
    headerLayout->addWidget(titleLabel);
    headerLayout->addWidget(avatarLabel);

    // Center the header layout
    headerLayout->setAlignment(Qt::AlignCenter);

    // Add the header layout to the main layout
    infoLayout->addLayout(headerLayout);

    // Add some spacing after the header
    infoLayout->addSpacing(20);

    // Create and style personal info labels with horizontal layout for pairs
    QHBoxLayout *nicknameGenderLayout = new QHBoxLayout();
    nicknameLabel = new QLabel(tr("昵称: "), this);
    genderLabel = new QLabel(tr("性别: "), this);
    nicknameGenderLayout->addWidget(nicknameLabel);
    nicknameGenderLayout->addWidget(genderLabel);
    infoLayout->addLayout(nicknameGenderLayout);

    // Add some spacing after the nickname and gender
    infoLayout->addSpacing(10);

    QHBoxLayout *emailSignLayout = new QHBoxLayout();
    emailLabel = new QLabel(tr("邮箱: "), this);
    signLabel = new QLabel(tr("个性签名: "), this);
    emailSignLayout->addWidget(emailLabel);
    emailSignLayout->addWidget(signLabel);
    infoLayout->addLayout(emailSignLayout);

    // Add some spacing after the email and signature
    infoLayout->addSpacing(10);

    // Add "Edit" button
    editButton = new QPushButton(tr("编辑"), this);
    infoLayout->addWidget(editButton);

    // Add some spacing after the edit button
    infoLayout->addSpacing(10);

    // Add "Address Management" button
    addressManageButton = new QPushButton(tr("地址管理"), this);
    addressManageButton->setStyleSheet(buttonStyle());  // Set button style
    infoLayout->addWidget(addressManageButton);

    // Add a spacer at the bottom to push everything up
    infoLayout->addStretch();
}



void UserPersonal::createOrderLayout(QVBoxLayout *orderLayout)
{
    orderLabels.clear();
    while (orderLayout->count() > 0) {
        QLayoutItem *item = orderLayout->takeAt(0);
        delete item->widget();
        delete item;
    }
    // 创建一个垂直布局来容纳多个订单项
    QVBoxLayout *ordersLayout = new QVBoxLayout();  // 这是容纳所有订单项的布局

    // 假设我们要动态创建多个订单项
    for (int i = 0; i < ordersArray.size(); ++i) {
        // 创建一个容器来容纳单个订单信息
        QFrame *orderContainer = new QFrame(this);
        orderContainer->setFrameShape(QFrame::StyledPanel);
        orderContainer->setLineWidth(2);
        QVBoxLayout *verticalLayout = new QVBoxLayout(orderContainer);

        // 创建商品信息布局（商品名称，购买数量，收件地址，商品价格，总价格）
        QHBoxLayout *productLayout = new QHBoxLayout();
        QLabel *productImageLabel = new QLabel(orderContainer);
        productImageLabel->setFixedSize(100, 100);  // 设置固定大小用于显示商品图片
        productLayout->addWidget(productImageLabel);

        QLabel *labelProductName = new QLabel("商品名称：", orderContainer);
        QLabel *labelProductNameValue = new QLabel(orderContainer);
        productLayout->addWidget(labelProductName);
        productLayout->addWidget(labelProductNameValue);

        QLabel *labelQuantity = new QLabel("购买数量：", orderContainer);
        QLabel *labelQuantityValue = new QLabel(orderContainer);
        productLayout->addWidget(labelQuantity);
        productLayout->addWidget(labelQuantityValue);

        QLabel *labelRecipientAddress = new QLabel("收件地址：", orderContainer);
        QLabel *labelAddressValue = new QLabel(orderContainer);
        productLayout->addWidget(labelRecipientAddress);
        productLayout->addWidget(labelAddressValue);

        QLabel *labelProductPrice = new QLabel("商品价格：", orderContainer);
        QLabel *labelUnitPriceValue = new QLabel(orderContainer);
        productLayout->addWidget(labelProductPrice);
        productLayout->addWidget(labelUnitPriceValue);

        QLabel *labelTotalPrice = new QLabel("总价格：", orderContainer);
        QLabel *labelTotalPriceValue = new QLabel(orderContainer);
        productLayout->addWidget(labelTotalPrice);
        productLayout->addWidget(labelTotalPriceValue);

        verticalLayout->addLayout(productLayout);

        // 创建订单详情布局（订单号，创建时间，收件人，收件电话，删除按钮）
        QHBoxLayout *orderLayoutDetails = new QHBoxLayout();
        QLabel *labelOrderID = new QLabel("订单号：", orderContainer);
        QLabel *labelOrderIDValue = new QLabel(orderContainer);
        orderLayoutDetails->addWidget(labelOrderID);
        orderLayoutDetails->addWidget(labelOrderIDValue);

        QLabel *labelCreateTime = new QLabel("创建时间：", orderContainer);
        QLabel *labelCreateTimeValue = new QLabel(orderContainer);
        orderLayoutDetails->addWidget(labelCreateTime);
        orderLayoutDetails->addWidget(labelCreateTimeValue);

        QLabel *labelRecipientName = new QLabel("收件人：", orderContainer);
        QLabel *labelRecipientNameValue = new QLabel(orderContainer);
        orderLayoutDetails->addWidget(labelRecipientName);
        orderLayoutDetails->addWidget(labelRecipientNameValue);

        QLabel *labelRecipientPhone = new QLabel("收件电话：", orderContainer);
        QLabel *labelRecipientPhoneValue = new QLabel(orderContainer);
        orderLayoutDetails->addWidget(labelRecipientPhone);
        orderLayoutDetails->addWidget(labelRecipientPhoneValue);

        verticalLayout->addLayout(orderLayoutDetails);


        OrderLabels *labels = new OrderLabels{
            labelOrderIDValue,
            labelCreateTimeValue,
            labelRecipientNameValue,
            labelRecipientPhoneValue,
            labelAddressValue,
            labelTotalPriceValue,
            labelProductNameValue,
            labelQuantityValue,
            labelUnitPriceValue,
            productImageLabel
        };

        // 存储这些标签以供后续使用
        orderLabels.append(labels);

        ordersLayout->addWidget(orderContainer);
    }

    // 创建一个滚动区域并将订单布局添加到其中
    QScrollArea *scrollArea = new QScrollArea(this);
    QWidget *scrollAreaWidget = new QWidget(this);
    scrollAreaWidget->setLayout(ordersLayout);
    scrollArea->setWidget(scrollAreaWidget);
    scrollArea->setWidgetResizable(true);

    // 将滚动区域添加到父布局
    orderLayout->addWidget(scrollArea);
}

void UserPersonal::displayOrderDetails(int index, int orderId, const QString &orderDate, double totalAmount, const QString &recipientName, const QString &recipientPhone, const QString &shippingAddress)
{
    if (index >= 0 && index < orderLabels.size()) {
        OrderLabels *labels = orderLabels[index];
        labels->labelOrderIDValue->setText(QString::number(orderId));
        labels->labelCreateTimeValue->setText(orderDate);
        labels->labelTotalPriceValue->setText(QString::number(totalAmount, 'f', 2));
        labels->labelRecipientNameValue->setText(recipientName);
        labels->labelRecipientPhoneValue->setText(recipientPhone);
        labels->labelAddressValue->setText(shippingAddress);
    }
}

void UserPersonal::displayProductDetails(int index, int quantity, double unitPrice)
{
    if (index >= 0 && index < orderLabels.size()) {
        OrderLabels *labels = orderLabels[index];
        labels->labelQuantityValue->setText(QString::number(quantity));
        labels->labelUnitPriceValue->setText(QString::number(unitPrice, 'f', 2));
    }
}

void UserPersonal::setProductDetails(int index, const QString &productName, const QPixmap &productImage)
{
    if (index >= 0 && index < orderLabels.size()) {
        OrderLabels *labels = orderLabels[index];
        labels->labelProductNameValue->setText(productName);
        labels->productImageLabel->setPixmap(productImage.scaled(labels->productImageLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
    }
}

void UserPersonal::fetchOrderList()
{
    int userId = UserSession::getInstance().getUserId();  // Get user ID

    // Set up request for order list
    QJsonObject parameters;
    parameters["userId"] = userId;

    PptpMessage requestMessage;
    requestMessage.setParameters(parameters);
    requestMessage.setPath("user/orderList");

    // Send the request to get order information
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &UserPersonal::onOrderListResponse);
}

void UserPersonal::onOrderListResponse(PptpMessage responseMessage)
{
    QJsonObject response = responseMessage.getParameters();
    qDebug() << "订单信息" << response;
    ordersArray = response["orders"].toArray();
    createOrderLayout(orderLayout);

    int index = 0; // 用于记录当前订单的索引
    for (const QJsonValue &orderValue : ordersArray)
    {
        QJsonObject orderObject = orderValue.toObject();
        int orderId = orderObject["order_id"].toInt();
        QString orderDate = orderObject["order_date"].toString();
        double totalAmount = orderObject["total_amount"].toDouble();
        QString recipientName = orderObject["name"].toString();
        QString recipientPhone = orderObject["phone"].toString();
        QString shippingAddress = orderObject["address"].toString();

        // Display the order details in the UI
        displayOrderDetails(index, orderId, orderDate, totalAmount, recipientName, recipientPhone, shippingAddress);

        QJsonArray itemsArray = orderObject["items"].toArray();

        // Loop through each item in the order to fetch additional details
        for (const QJsonValue &itemValue : itemsArray)
        {
            QJsonObject itemObject = itemValue.toObject();
            int productId = itemObject["product_id"].toInt();
            int quantity = itemObject["quantity"].toInt();
            double unitPrice = itemObject["price"].toDouble();

            // Display the product details in the UI
            displayProductDetails(index, quantity, unitPrice);

            // Request product image
            fetchProductDetails(productId);
        }

        index++; // 更新索引
    }
}

void UserPersonal::fetchProductDetails(int productId)
{
    QJsonObject parameters;
    parameters["product_id"] = productId;

    PptpMessage requestMessage;
    requestMessage.setParameters(parameters);
    requestMessage.setPath("product/getProductsById");

    // Send the request to get product details
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &UserPersonal::onProductDetailsResponse);
}

void UserPersonal::onProductDetailsResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    qDebug()<<responseParameters;
    QString productName = responseParameters["productName"].toString();
    QHash<QString, QByteArray> files = responseMessage.getFiles();

    // Extract product ID from the response to use as the filename key for the image
    int productId = responseParameters["product_id"].toInt();
    QString filename = QString::number(productId);

    // Retrieve the image data from the response files using the filename
    QByteArray imageData = files.value(filename);
    if (!imageData.isEmpty())
    {
        QPixmap productImage;
        productImage.loadFromData(imageData);  // Load image data into QPixmap

        // Find the correct index for the product


        for (imgindex; imgindex < ordersArray.size(); ++imgindex)
        {
            QJsonObject orderObject = ordersArray[imgindex].toObject();
            QJsonArray itemsArray = orderObject["items"].toArray();
            for (const QJsonValue &itemValue : itemsArray)
            {
                //QJsonObject itemObject = itemValue.toObject();
                // if (itemObject["product_id"].toInt() == productId)
                // {
                     indexlen = imgindex;
                    ++imgindex;
                     break;
                // }

            }
            if (indexlen != -1) break;
        }

        if (indexlen != -1)
        {
            setProductDetails(indexlen, productName, productImage);
            qDebug() << "Product Image stored for Product ID:" << productId;
        }
        else
        {
            qDebug() << "No matching order found for Product ID:" << productId;
        }
    }
    else
    {
        qDebug() << "No image data found for Product ID:" << productId;
    }
}

UserPersonal::~UserPersonal() {

}

